<template>
	<div class="branch-wrap">
		<div class="branch-box-wrap">
			<div class="branch-box">
				<el-button class="add-branch" type="success" plain round @click="addTerm">添加条件</el-button>
				<div class="col-box" v-for="(item,index) in nodeConfig.conditionNodes" :key="index">
					<div class="condition-node">
						<div class="condition-node-box">
							<div class="auto-judge" @click="show(index)">
								<div class="sort-left" v-if="index!=0" @click.stop="arrTransfer(index,-1)">
									<el-icon style="margin-left: 3px;"><el-icon-arrow-left /></el-icon>
								</div>
								<div class="title">
									<span class="node-title">{{ item.nodeName }}</span>
									<span class="priority-title">优先级{{item.priorityLevel}}</span>
									<el-icon class="close" @click.stop="delTerm(index)"><el-icon-close /></el-icon>
									<el-icon class="show" @click.stop="showForm(index)"><el-icon-view /></el-icon>
								</div>
								<div class="content">
									<span v-if="toText(nodeConfig, index)">{{ toText(nodeConfig, index) }}</span>
									<span v-else class="placeholder">请设置条件</span>
								</div>
								<div class="sort-right" v-if="index!=nodeConfig.conditionNodes.length-1" @click.stop="arrTransfer(index)">
									<el-icon style="margin-right: 3px;"><el-icon-arrow-right /></el-icon>
								</div>
							</div>
							<add-node v-model="item.childNode" :parent-data="nodeConfig"></add-node>
						</div>
					</div>
					<slot v-if="item.childNode" :node="item"></slot>
					<div class="top-left-cover-line" v-if="index==0"></div>
					<div class="bottom-left-cover-line" v-if="index==0"></div>
					<div class="top-right-cover-line" v-if="index==nodeConfig.conditionNodes.length-1"></div>
					<div class="bottom-right-cover-line" v-if="index==nodeConfig.conditionNodes.length-1"></div>
				</div>
			</div>
			<add-node v-model="nodeConfig.childNode" :parent-data="nodeConfig"></add-node>
		</div>
		<el-drawer title="条件设置" v-model="drawer" destroy-on-close append-to-body :size="600">
			<template #header>
				<div class="node-wrap-drawer__title">
					<label @click="editTitle" v-if="!isEditTitle">{{form.nodeName}}<el-icon class="node-wrap-drawer__title-edit"><el-icon-edit /></el-icon></label>
					<el-input v-if="isEditTitle" ref="nodeTitle" v-model="form.nodeName" clearable @blur="saveTitle" @keyup.enter="saveTitle"></el-input>
				</div>
			</template>
			<el-container>
				<el-main style="padding:0 20px 20px 20px">
					<el-form label-position="top">
						<el-form-item label="条件关系">
							<el-radio-group v-model="form.conditionMode">
								<el-radio :label="1">且</el-radio>
								<el-radio :label="2">或</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-divider></el-divider>
						<el-form-item label="表单">
							<el-select placeholder="请选择表单" v-model="form.formId" @change="changeForm">
								<el-option v-for="item in formList" :label="item.formName" :value="item.id" :key="item.id"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item v-show="form.formId != null">
							<el-table :data="form.conditionList">
								<el-table-column prop="label" label="描述">
									<template #default="scope">
										<el-input v-model="scope.row.label" placeholder="描述"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="field" label="条件字段" width="130">
									<template #default="scope">
										<el-select v-model="scope.row.field" placeholder="条件字段" ref="field" @change="changeField(scope)" style="width: 100%;">
											<el-option v-for="item in formFieldList" :label="item.fieldName" :value="item.field" :key="item.field"></el-option>
										</el-select>
<!--										<el-input v-model="scope.row.field" placeholder="条件字段"></el-input>-->
									</template>
								</el-table-column>
								<el-table-column prop="operator" label="运算符" width="130">
									<template #default="scope">
										<el-select v-model="scope.row.operator" placeholder="Select" style="width: 100%;">
											<el-option label="等于" value="=="></el-option>
											<el-option label="不等于" value="!="></el-option>
											<el-option label="大于" value=">"></el-option>
											<el-option label="大于等于" value=">="></el-option>
											<el-option label="小于" value="<"></el-option>
											<el-option label="小于等于" value="<="></el-option>
											<el-option label="包含" value="contains"></el-option>
											<el-option label="不包含" value="notinclude"></el-option>
										</el-select>
									</template>
								</el-table-column>
								<el-table-column prop="value" label="值" width="100">
									<template #default="scope">
										<el-input v-model="scope.row.value" @blur="changeValue(scope)" placeholder="值"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="value" label="移除" width="55">
									<template #default="scope">
										<el-link type="danger" :underline="false" @click="deleteConditionList(scope.$index)">移除</el-link>
									</template>
								</el-table-column>
							</el-table>
						</el-form-item>
						<p  v-show="form.formId != null"><el-button type="primary" icon="el-icon-plus" round @click="addConditionList">增加条件</el-button></p>
					</el-form>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="save">保存</el-button>
					<el-button @click="drawer=false">取消</el-button>
				</el-footer>
			</el-container>
		</el-drawer>
	</div>
</template>

<script>
	import addNode from './addNode'
	import {inject} from "vue";
	import SnowflakeId from "snowflake-id";

	export default {
		inject: ['flowModelData'],
		props: {
			modelValue: { type: Object, default: () => {} }
		},
		components: {
			addNode
		},
		data() {
			return {
				flowModeData: inject('flowModelData') ||{},
				nodeConfig: {},
				drawer: false,
				isEditTitle: false,
				index: 0,
				form: {},
				// 流程图数据
				flowData:null,
				// 审批节点集合
				nodeList:[],
				// 父级节点
				parentNode:null,
				// 字段集合
				fieldOption:[],
				// 表单ID
				formId:null,
				// 表单集合
				formList:[],
				// 表单字段集合
				formFieldList:[],
				snowflake:null,
			}
		},

		watch:{
			modelValue(){
				this.nodeConfig = this.modelValue
			}
		},
		mounted() {
			const snowflake = new SnowflakeId({
				mid: 42,
				offset: (2019 - 1970) * 31536000 * 1000
			});
			this.snowflake =snowflake;
			this.nodeConfig = this.modelValue
			let appId = this.$route.query.appId;
			this.getAllForm(appId)
			// this.flowData=this.flowModelData;
			// console.log(this.flowData)
			// this.getParentForm();
		},
		methods: {
			show(index){
				this.index = index
				this.form = {}
				this.form = JSON.parse(JSON.stringify(this.nodeConfig.conditionNodes[index]))
				this.drawer = true
			},
			editTitle(){
				this.isEditTitle = true
				this.$nextTick(()=>{
					this.$refs.nodeTitle.focus()
				})
			},
			saveTitle(){
				this.isEditTitle = false
			},
			save(){
				this.nodeConfig.conditionNodes[this.index] = this.form
				this.$emit("update:modelValue", this.nodeConfig)
				this.drawer = false
			},
			addTerm(){
				let len = this.nodeConfig.conditionNodes.length + 1
				this.nodeConfig.conditionNodes.push({
					id: "node_"+this.snowflake.generate(),
					nodeName: "条件" + len,
					type: 3,
					priorityLevel: len,
					conditionMode: 1,
					conditionList: [],
				})
			},
			// 获取父级表单所有字段
			getParentForm(){
				this.getParentNode()
			},
			getParentNode(){
				// TODO 后期优化
				this.getNodeById(this.nodeConfig.parentId,this.flowData.nodeConfig)
				console.log('getParentNode',this.flowData)
				if (this.parentNode == null){
					// 开始节点
					this.getFormOption(this.flowData.nodeConfig)
					this.nodeConfig.conditionNodes.map((item)=>{
						item.parentApprover=JSON.stringify({id:this.flowData.nodeConfig.id,dataForm:this.flowData.nodeConfig.dataForm,nodeForm:this.flowData.nodeConfig.nodeForm})
					})
				}else {
					this.getFormOption(this.parentNode)
					let _this =this;
					this.nodeConfig.conditionNodes.map((item)=>{
						 item.parentApprover=JSON.stringify({id:_this.parentNode.id,dataForm:_this.parentNode.dataForm,nodeForm:_this.parentNode.nodeForm})
					})
				}
			},
			// 显示表单
			showForm(i){
				console.log("显示表单",i)
			},
			// 根据id获取节点
			getNodeById(id,nodeList){
				if (
					typeof nodeList !== 'object' ||
					JSON.stringify(nodeList) === '{}' ||
					nodeList == null ||
					Array.isArray(nodeList)
				) {
					return
				}
				if (nodeList.id == id){
					if (nodeList.type != 1){
						this.getNodeById(nodeList.parentId,this.flowData);
					}else {
						this.parentNode=nodeList;
					}
				}
				switch (nodeList.type){
					case 0:
						this.getNodeById(id,nodeList.childNode);
						break
					case 1:
						this.getNodeById(id,nodeList.childNode);
						break
					case 5:
						nodeList.branchs.forEach((item)=>{
							this.getNodeById(id,item.childNode)
						})
						break;
					case 4:
						nodeList.conditionNodes.forEach((item)=>{
							this.getNodeById(id,item.childNode)
						})
						break;
					default:
						this.getNodeById(id,nodeList.childNode)
						break
				}
			},
			// 获取表单
			async getFormOption(nodeConfig) {
				console.log("getFormOption",nodeConfig)
				if (nodeConfig.type == 0) {
					// 开始节点配置表单
					let res = await this.$API.app.form.getDetails.get(nodeConfig.dataForm);
					if (res.code == 200){
						 let item = JSON.parse(res.data.formTemplate)
						item.formFields.map((item)=>{
						    this.fieldOption.push({label:item.title,value:item.field})
						})
					}
				} else {
					// 获取节点配置表单
					if (nodeConfig.formType == 1) {
						// 同步开始节点
						this.parentNode.dataForm=this.flowData.nodeConfig.dataForm
						this.parentNode.nodeForm=this.flowData.nodeConfig.nodeForm
						let res = await this.$API.app.form.getDetails.get(this.flowData.nodeConfig.dataForm);
						if (res.code == 200){
							let item = JSON.parse(res.data.formTemplate)
							item.formFields.map((item)=>{
								this.fieldOption.push({label:item.title,value:item.field})
							})
						}
					} else if (nodeConfig.formType == 3) {
						// 选择表单
						this.parentNode.dataForm=nodeConfig.dataForm
						this.parentNode.nodeForm=nodeConfig.nodeForm
						let res = await this.$API.app.form.getDetails.get(nodeConfig.dataForm);
						if (res.code == 200){
							let item = JSON.parse(res.data.formTemplate)
							item.formFields.map((item)=>{
								this.fieldOption.push({label:item.title,value:item.field})
							})
						}
					} else if (nodeConfig.formType == 4) {
						// TODO 节点表单

					}
				}
			},
			// 根据应用ID获取所有表单
			async getAllForm(appId) {
				let res = await this.$API.app.form.getAppForm.get(appId);
				if (res.code == 200){
					this.formList = res.data;
				}
			},
			// 表单改变
			async changeForm(env) {
				let res = await this.$API.app.form.getFormField.get(env);
				if (res.code == 200){
					res.data.map((item) =>{
						if (typeof(item.field) !='undefined'){
							this.formFieldList.push(item)
						}
					})
				}
			},
			// 字段改变
			changeField(scope){
				this.$nextTick(()=>{
					scope.row.label=this.$refs.field.selectedLabel;
				})
			},
			// 值改变
			changeValue(scope){
				 scope.row.value= '"'+scope.row.value+'"';
			},
			delTerm(index){
				this.nodeConfig.conditionNodes.splice(index, 1)
				if (this.nodeConfig.conditionNodes.length == 1) {
					if (this.nodeConfig.childNode) {
						if (this.nodeConfig.conditionNodes[0].childNode) {
							this.reData(this.nodeConfig.conditionNodes[0].childNode, this.nodeConfig.childNode)
						}else{
							this.nodeConfig.conditionNodes[0].childNode = this.nodeConfig.childNode
						}
					}
					this.$emit("update:modelValue", this.nodeConfig.conditionNodes[0].childNode);
				}
			},
			reData(data, addData) {
				if (!data.childNode) {
					data.childNode = addData
				} else {
					this.reData(data.childNode, addData)
				}
			},
			arrTransfer(index, type = 1){
				this.nodeConfig.conditionNodes[index] = this.nodeConfig.conditionNodes.splice(index + type, 1, this.nodeConfig.conditionNodes[index])[0]
				this.nodeConfig.conditionNodes.map((item, index) => {
					item.priorityLevel = index + 1
				})
				this.$emit("update:modelValue", this.nodeConfig)
			},
			addConditionList(){
				this.form.conditionList.push({
					label: '',
					field: '',
					operator: '==',
					value: ''
				})
			},
			deleteConditionList(index){
				this.form.conditionList.splice(index, 1)
			},
			toText(nodeConfig, index){
				var { conditionList } = nodeConfig.conditionNodes[index]

				if (conditionList && conditionList.length == 1) {
					const text = conditionList.map(item => `${item.label}${item.operator}${item.value}`).join(" 和 ")
					return text
				}else if(conditionList && conditionList.length > 1){
					const conditionModeText = nodeConfig.conditionNodes[index].conditionMode==1?'且行':'或行'
					return conditionList.length + "个条件，" + conditionModeText
				}else{

					if(index == nodeConfig.conditionNodes.length - 1){
						return "其他条件进入此流程"
					}else{
						return false
					}
				}
			}
		}
	}
</script>

<style>
</style>
